import os
import uuid

import yaml
from core.globalContext import G_context
from parse.DataRandom import random_data


def yaml_read(filepath):
    with open(filepath, 'r', encoding='utf-8') as file:
        data = yaml.full_load(file)
    return data

def get_yaml_updata(filepath):
    caseinfo = [ ]
    case_info = yaml_read(filepath)
    caseinfo.append(case_info)
    return caseinfo

def get_data_from_yaml(filepath):
    file_yaml=os.path.join(filepath,'context.yaml')
    context = yaml_read(file_yaml)
    G_context().update_dict(context)
    G_context().set_dict('account', random_data())

def load_yaml_files(filepath):
     file_yaml = []
     case_info = []
     try:
         filenames = os.listdir(filepath)
         #
         for filename in filenames:
             if filename.endswith('.yaml') and (filename.split('_')[0]).isdigit():
                 file_value = filename.split('_')[0]
                 file_yaml.append((file_value, filename))
         file_yaml.sort()
         yaml_names = [filename[1] for filename in file_yaml]
         print('yaml name is' , yaml_names)
         for yaml_name in yaml_names:
             yaml_file = os.path.join(filepath, yaml_name)
             print('yaml file is',yaml_file)
             caseinfo=yaml_read(yaml_file)
             print ('case info is', caseinfo)
             case_info.append(caseinfo)
         print ('case info is', case_info)
     except Exception as e:
         print(filenames, yaml_file)
     return case_info


def yaml_case_parse(filepath):
    caseinfos = []
    casenames = []
    yaml_case_info = load_yaml_files(filepath)
    for caseinfo in yaml_case_info:
        casename = caseinfo.get('desc',uuid.uuid4().__str__())
        caseinfo.update({'_case_name': casename})
        caseinfos.append(caseinfo)
        casenames.append(casename)
    return {'casenames':casenames,
            'caseinfos':caseinfos}


if __name__ == '__main__':
    filepath = r'C:\peipei_study\接口自动化\examples\yaml_testcase'
    case_info=yaml_case_parse(filepath)
    print(case_info)
   # case_info= eval('case_info')
   # case_info = case_info['caseinfos']
    #print (case_info)
    rs= 'id, name'
    rs=rs.split(',')
    print (rs)



